﻿using AutoMapper;
using B.S.GridManage.Api.Write.Application.Command.LogicalGrid;
using B.S.GridManage.Domain.Entities;
using B.S.GridManage.ErrorCode;
using B.S.GridManage.Infrastructure.Interface;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.GridManage.Api.Write.Application.Handler.LogicalGrid
{
    public class CreateLogicalGridHandler : IRequestHandler<CreateLogicalGridCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<LogicalGridModel> logicalRepo;
        private readonly IMapper mapper;
        private readonly ILogger<CreateLogicalGridHandler> logger;

        public CreateLogicalGridHandler(IBaseRepository<LogicalGridModel> logicalRepo,IMapper mapper ,ILogger<CreateLogicalGridHandler> logger)
        {
            this.logicalRepo = logicalRepo;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<ApiResult<int>> Handle(CreateLogicalGridCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();//实例化响应包装类

            //判断名称和编码唯一
            var logicalGrid = logicalRepo.GetAll().Where(x=>x.GridName==request.GridName||x.GridCode==request.GridCode).FirstOrDefault();

            if (logicalGrid != null) {
                res.Msg = "网格名称或编码已经存在!";
                res.Code = ApiEnum.Failed;
            }




            //把request 转为Model
            var model  = mapper.Map<LogicalGridModel>(request);
            model.Id  = YitIdHelper.NextId();//别忘了雪花id

            int r = await logicalRepo.CreateAsync(model);
            if (r > 0)
            {
                res.Msg = "添加逻辑网格成功!";
                res.Code = ApiEnum.Success;
                res.Data = r;
            }
            else
            {
                res.Msg = "添加逻辑网格失败!";
                res.Code = ApiEnum.Failed;
                res.Data = r;
            }
            return res;


        }
    }
}
